package org.example;

import constant.UserType;
import exception.InvalidPasswordException;
import exception.UserNotFoundException;
import service.*;
import util.DBUtil;
import util.InputUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.*;

import static constant.UserType.*;
import static service.UserService.stmt;
import static util.DBUtil.conn;

public class Main {
    private static String username=null;

    public static void main(String[] args) {
        try {
            DBUtil.init();
            Statement statement=conn.createStatement();
            statement.execute("DELETE FROM movies");
            if(isempty1()) {
                statement.execute("CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, password TEXT, user_type TEXT, need_change_password INTEGER)");
                statement.execute("INSERT INTO users (username, password, user_type, need_change_password) VALUES ('admin', 'admin123', 'ADMIN', 0)");
                statement.execute("INSERT INTO users (username, password, user_type, need_change_password) VALUES ('manager', 'manager123', 'MANAGER', 0)");
                statement.execute("INSERT INTO users (username, password, user_type, need_change_password) VALUES ('receptionist', 'receptionist123', 'RECEPTIONIST', 0)");
            }
            if(isempty2()) {
                statement.execute("CREATE TABLE IF NOT EXISTS movies (movie_id TEXT PRIMARY KEY, title TEXT, director TEXT, duration INTEGER, genre TEXT, description TEXT)");
                statement.execute("INSERT INTO movies (movie_id, title, director, duration, genre, description) VALUES ('M001', '复仇者联盟4', '安东尼·罗素', 181, '科幻/冒险', '复仇者联盟的终局之战')");
                statement.execute("INSERT INTO movies (movie_id, title, director, duration, genre, description) VALUES ('M002', '流浪地球2', '郭帆', 173, '科幻/灾难', '人类为了逃离太阳系的冒险')");
            }
            if(isempty3()){
                statement.execute("CREATE TABLE IF NOT EXISTS orders(order_id TEXT PRIMARY KEY, title TEXT, stime TEXT, seat TEXT, price REAL, state TEXT, order_time TEXT,user_name TEXT,room TEXT)");
                statement.execute("INSERT INTO orders (order_id, title, stime, seat,price, state, order_time,user_name,room) VALUES ('S001', '复仇者联盟4', '2025-07-16 10:00', '1,2', 50.0, '待支付', '2025-04-30 09:30','系统','1号厅')");
                statement.execute("INSERT INTO orders (order_id, title, stime, seat,price, state, order_time,user_name,room) VALUES ('S002', '复仇者联盟4', '2025-07-16 14:00', '2,3', 50.0, '待支付', '2025-04-30 09:45','系统','2号厅')");
                statement.execute("INSERT INTO orders (order_id, title, stime, seat,price, state, order_time,user_name,room) VALUES ('S003', '流浪地球2', '2025-07-16 19:00', '1,5', 45.0, '待支付', '2025-04-30 09:45','系统','3号厅')");

            }//"订单号", "电影名称", "放映时间", "座位", "总价", "状态", "下单时间");
            if(isempty4()) {
                statement.execute("CREATE TABLE IF NOT EXISTS rooms(id TEXT PRIMARY KEY, capacity INTEGER, name TEXT)");
                statement.execute("INSERT INTO rooms (id, capacity, name) VALUES ('R001', 100, '1号厅')");
                statement.execute("INSERT INTO rooms (id, capacity, name) VALUES ('R002', 80, '2号厅')");
                statement.execute("INSERT INTO rooms (id, capacity, name) VALUES ('R003', 60, '3号厅')");
            }
                statement.execute("CREATE TABLE IF NOT EXISTS logs(user_name TEXT, action TEXT, action_time TEXT)");
                statement.execute("CREATE TABLE IF NOT EXISTS screening(id TEXT, movie TEXT, room TEXT, start_time TEXT, price REAL)");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }//创建数据库对象及表

        System.out.println("=============================================");
        System.out.println("=========== 万东电影院管理系统 v1.0 ===========");
        System.out.println("=============================================\n");

        while (true) {
            if (username== null) {
                showLoginMenu();
            } else {
                switch (GUT()) {
                    case ADMIN:
                        showAdminMenu();
                        break;
                    case MANAGER:
                        showManagerMenu();
                        break;
                    case RECEPTIONIST:
                        showReceptionistMenu();
                        break;
                    case null:
                        break;
                }
            }
        }
    }

    private static boolean isempty4() {
        try(Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery("SELECT COUNT(*) FROM rooms")) {
            return rs.next() && rs.getInt(1)==0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static boolean isempty3() {
        try(Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery("SELECT COUNT(*) FROM orders")) {
            return rs.next() && rs.getInt(1)==0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static UserType GUT() {
        try(PreparedStatement ptmt=conn.prepareStatement("SELECT user_type FROM users WHERE username=?");){
            ptmt.setString(1,username);
            ResultSet rs=ptmt.executeQuery();
            if(rs.next()) {
                String typeStr = rs.getString("user_type");
                return valueOf(typeStr); // 直接返回枚举对象
            }
            else{
                return null;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static boolean isempty2() {
        try(Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery("SELECT COUNT(*) FROM movies")) {
            return rs.next() && rs.getInt(1)==0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static boolean isempty1() {
        try(Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery("SELECT COUNT(*) FROM users")) {
            return rs.next() && rs.getInt(1)==0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 显示登录菜单
    private static void showLoginMenu() {
        System.out.println("\n===== 登录菜单 =====");
        System.out.println("1. 登录");
        System.out.println("2. 退出系统");
        System.out.println("====================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                handleLogin();
                break;
            case 2:
                System.out.println("感谢使用万东电影院管理系统，再见！");
                System.exit(0);
                break;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 处理登录操作
    private static void handleLogin() {
        String user_name = InputUtils.inputString("请输入用户名: ");
        String password = InputUtils.inputString("请输入密码: ");
        Boolean isneed;

        try(PreparedStatement pt=conn.prepareStatement("SELECT need_change_password FROM users WHERE username=?");){
            pt.setString(1,user_name);
            ResultSet rs=pt.executeQuery();
            isneed=rs.next() && rs.getBoolean(1);
            username= UserService.login(user_name, password);
//            currentUser = user;
            System.out.println("登录成功！欢迎您，" + username + "！");

            // 如果需要修改密码，则强制修改
            if (isneed) {
                System.out.println("您的密码为初始密码，请立即修改！");
                String newPassword = InputUtils.inputString("请输入新密码: ");
                UserService.changePassword(username, password, newPassword);
                System.out.println("密码修改成功！");
            }
        } catch (UserNotFoundException | InvalidPasswordException | SQLException e) {
            System.out.println("登录失败: " + e.getMessage());
        }
    }

    // 显示管理员菜单
    private static void showAdminMenu() {
        // 打印管理员菜单
        System.out.println("\n===== 管理员菜单 =====");
        System.out.println("1. 密码管理");
        System.out.println("2. 用户管理");
        System.out.println("3. 查看日志");
        System.out.println("4. 退出登录");
        System.out.println("======================");

        // 获取用户输入的操作
        int choice = InputUtils.inputInt("请选择操作: ");

        // 根据用户输入的操作执行相应的操作
        switch (choice) {
            case 1:
                // 显示密码管理菜单
                showAdminPasswordMenu();
                break;
            case 2:
                // 显示用户管理菜单
                showAdminUserManagementMenu();
                break;
            case 3:
                // 打印所有日志
                LogService.printAllLogs();
                break;
            case 4:
                // 退出登录
                System.out.println("退出登录成功！");
                username= null;
                break;
            default:
                // 无效的选择
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 显示密码管理菜单
    private static void showAdminPasswordMenu() {
        System.out.println("\n===== 密码管理 =====");
        System.out.println("1. 修改自身密码");
        System.out.println("2. 重置用户密码");
        System.out.println("3. 返回上一级");
        System.out.println("====================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                handleChangeOwnPassword();
                break;
            case 2:
                handleResetUserPassword();
                break;
            case 3:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 修改自身密码
    private static void handleChangeOwnPassword() {
        try {
            // 输入旧密码
            String oldPassword = InputUtils.inputString("请输入旧密码: ");
            // 输入新密码
            String newPassword = InputUtils.inputString("请输入新密码: ");
            // 调用UserService的changePassword方法，修改密码
            UserService.changePassword(username, oldPassword, newPassword);
            // 输出密码修改成功
            System.out.println("密码修改成功！");
        } catch (InvalidPasswordException e) {
            // 输出修改密码失败的信息
            System.out.println("修改密码失败: " + e.getMessage());
        }
    }

    // 重置用户密码
    private static void handleResetUserPassword() {
        String un = InputUtils.inputString("请输入要重置密码的用户名: ");

        if (un.equals(username)) {
            System.out.println("不能重置自己的密码！");
            return;
        }

        try {
            UserService.resetPassword(username, "123456");
            System.out.println("用户 " + username + " 的密码已重置为: 123456");
        } catch (UserNotFoundException e) {
            System.out.println("重置失败: " + e.getMessage());
        }
    }

    // 显示用户管理菜单
    private static void showAdminUserManagementMenu() {
        System.out.println("\n===== 用户管理 =====");
        System.out.println("1. 查看所有用户");
        System.out.println("2. 添加用户");
        System.out.println("3. 删除用户");
        System.out.println("4. 返回上一级");
        System.out.println("====================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                showAllUsers();
                break;
            case 2:
                handleAddUser();
                break;
            case 3:
                handleDeleteUser();
                break;
            case 4:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 显示所有用户
    private static void showAllUsers() {
        System.out.println("\n===== 用户列表 =====");
        System.out.printf("%-10s %-20s %-15s %s\n", "用户名", "用户类型", "初始密码", "状态");
        try {
            ResultSet rs=stmt.executeQuery("SELECT * FROM users");
            System.out.println("用户名"+"       "+"用户密码"+"      "+"用户类型"+"      "+"是否需要修改密码");
            while(rs.next()){
                System.out.println(rs.getString("username")+"      "+rs.getString("password")+"       "+rs.getString("user_type")+"       "+rs.getBoolean("need_change_password"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("===================");
    }

    // 添加用户
    private static void handleAddUser() {
        String username = InputUtils.inputString("请输入用户名: ");

        try {
            PreparedStatement pt = conn.prepareStatement("SELECT 1 FROM users WHERE username=?");
            pt.setString(1,username);
            ResultSet rs=pt.executeQuery();
            if(rs.next()){
                System.out.println("添加失败: 用户名已存在！");
                return;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        System.out.println("请选择用户类型:");
        System.out.println("1. 管理员");
        System.out.println("2. 经理");
        System.out.println("3. 前台");
        int typeChoice = InputUtils.inputInt("请选择: ");

        UserType userType;
        switch (typeChoice) {
            case 1:
                userType = ADMIN;
                break;
            case 2:
                userType = MANAGER;
                break;
            case 3:
                userType = RECEPTIONIST;
                break;
            default:
                System.out.println("无效的选择！");
                return;
        }

        UserService.addUser(username, "123456", userType);
        System.out.println("用户 " + username + " 创建成功，初始密码: 123456");
    }

    // 删除用户
    private static void handleDeleteUser() {
        String user_name = InputUtils.inputString("请输入要删除的用户名: ");

        if (user_name.equals(username)) {
            System.out.println("不能删除自己！");
            return;
        }

        try {
            UserService.deleteUser(user_name,username);
            System.out.println("用户 " + user_name + " 已删除！");
        } catch (UserNotFoundException e) {
            System.out.println("删除失败: " + e.getMessage());
        }
    }

    // 显示经理菜单
    private static void showManagerMenu() {
        System.out.println("\n===== 经理菜单 =====");
        System.out.println("1. 密码管理");
        System.out.println("2. 电影管理");
        System.out.println("3. 放映厅管理");
        System.out.println("4. 场次管理");
        System.out.println("5. 销售统计");
        System.out.println("6. 退出登录");
        System.out.println("====================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                showManagerPasswordMenu();
                break;
            case 2:
                showMovieManagementMenu();
                break;
            case 3:
                showScreeningRoomManagementMenu();
                break;
            case 4:
                showScreeningManagementMenu();
                break;
            case 5:
                showSalesStatistics();
                break;
            case 6:
                System.out.println("退出登录成功！");
                username= null;
                break;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 显示密码管理菜单
    private static void showManagerPasswordMenu() {
        System.out.println("\n===== 密码管理 =====");
        System.out.println("1. 修改自身密码");
        System.out.println("2. 返回上一级");
        System.out.println("====================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                handleChangeOwnPassword();
                break;
            case 2:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 显示电影管理菜单
    private static void showMovieManagementMenu() {
        System.out.println("\n===== 电影管理 =====");
        System.out.println("1. 查看所有电影");
        System.out.println("2. 添加电影");
        System.out.println("3. 修改电影信息");
        System.out.println("4. 删除电影");
        System.out.println("5. 返回上一级");
        System.out.println("====================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                showAllMovies();
                break;
            case 2:
                handleAddMovie();
                break;
            case 3:
                handleUpdateMovie();
                break;
            case 4:
                handleDeleteMovie();
                break;
            case 5:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 显示所有电影
    private static void showAllMovies() {
        System.out.println("\n===== 电影列表 =====");
        System.out.printf("%-10s %-20s %-15s %-10s %-10s %s\n", "ID", "电影名称", "导演", "时长(分钟)", "类型", "描述");
        try(PreparedStatement ptmt=conn.prepareStatement("SELECT * FROM movies")){
            ResultSet rs=ptmt.executeQuery();
            while (rs.next()) {
                System.out.printf("%-10s %-20s %-15s %-10d %-10s %s\n",
                        rs.getString("movie_id"),
                        rs.getString("title"),
                        rs.getString("director"),
                        rs.getInt("duration"),
                        rs.getString("genre"),
                        rs.getString("description"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("===================");
    }

    // 添加电影
    private static void handleAddMovie() {
        String id = InputUtils.inputString("请输入电影ID: ");
        String name = InputUtils.inputString("请输入电影名称: ");
        String director = InputUtils.inputString("请输入导演: ");
        int duration = InputUtils.inputInt("请输入时长(分钟): ");
        String genre = InputUtils.inputString("请输入类型: ");
        String description = InputUtils.inputString("请输入描述: ");

        MovieService.addMovie(id, name, director, duration, genre, description);
        System.out.println("电影 " + name + " 添加成功！");
    }

    // 修改电影信息
    private static void handleUpdateMovie() {
        String id = InputUtils.inputString("请输入要修改的电影ID: ");
        String title="";
        String director="";
        int duration=0;
        String genre="";
        String description="";
        try {
            PreparedStatement ptmt=conn.prepareStatement("SELECT title, director, duration, genre, description FROM movies WHERE movie_id=?");
            ptmt.setString(1, id);
            ResultSet rs=ptmt.executeQuery();
            if(rs.next()) {
                title = rs.getString("title");
                director=rs.getString("director");
                duration=rs.getInt("duration");
                genre=rs.getString("genre");
                description=rs.getString("description");
                System.out.println("当前电影信息:");
                System.out.printf("ID: %s\n名称: %s\n导演: %s\n时长: %d分钟\n类型: %s\n描述: %s\n",
                        id, title, director,
                        duration, genre, description);
            }
            else{
                System.out.println("电影不存在！");
                return;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        String new_title = InputUtils.inputString("请输入新的电影名称(留空不修改): ");
        String new_director = InputUtils.inputString("请输入新的导演(留空不修改): ");
        String durationStr = InputUtils.inputString("请输入新的时长(分钟)(留空不修改): ");
        int new_duration = durationStr.isEmpty() ? duration : Integer.parseInt(durationStr);
        String new_genre = InputUtils.inputString("请输入新的类型(留空不修改): ");
        String new_description = InputUtils.inputString("请输入新的描述(留空不修改): ");

        // 如果用户输入为空，则使用原来的值
        if (new_title.isEmpty()) new_title =title;
        if (new_director.isEmpty()) new_director = director;
        if (new_genre.isEmpty()) new_genre =genre;
        if (new_description.isEmpty()) new_description =description;

        MovieService.updateMovie(id,new_title,new_director,new_duration,new_genre,new_description);
        System.out.println("电影信息更新成功！");
    }

    // 删除电影
    private static void handleDeleteMovie() {
        String id = InputUtils.inputString("请输入要删除的电影ID: ");
        if(MovieService.deleteMovie(id)) {
            System.out.println("电影删除成功！");
        }
    }

    // 显示放映厅管理菜单
    private static void showScreeningRoomManagementMenu() {
        System.out.println("\n===== 放映厅管理 =====");
        System.out.println("1. 查看所有放映厅");
        System.out.println("2. 添加放映厅");
        System.out.println("3. 修改放映厅信息");
        System.out.println("4. 删除放映厅");
        System.out.println("5. 返回上一级");
        System.out.println("=======================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                showAllScreeningRooms();
                break;
            case 2:
                handleAddScreeningRoom();
                break;
            case 3:
                handleUpdateScreeningRoom();
                break;
            case 4:
                handleDeleteScreeningRoom();
                break;
            case 5:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 显示所有放映厅
    private static void showAllScreeningRooms() {
        System.out.println("\n===== 放映厅列表 =====");
        System.out.printf("%-10s %-20s %s\n", "ID", "名称", "座位数");
        try(PreparedStatement ptmt=conn.prepareStatement("SELECT id, name, capacity FROM rooms");){
            ResultSet rs=ptmt.executeQuery();
            while(rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("name");
                int capacity = rs.getInt("capacity");
                System.out.printf("%-10s %-20s %d\n", id, name, capacity);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("=====================");
    }

    // 添加放映厅
    private static void handleAddScreeningRoom() {
        String id = InputUtils.inputString("请输入放映厅ID: ");
        String name = InputUtils.inputString("请输入放映厅名称: ");
        int capacity = InputUtils.inputInt("请输入座位数: ");
        try(PreparedStatement pmt=conn.prepareStatement("SELECT 1 FROM rooms WHERE id=?")){
            pmt.setString(1,id);
            ResultSet rs=pmt.executeQuery();
            if(rs.next()) {
                System.out.println("放映厅ID已存在！");
                return;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try(PreparedStatement ptmt=conn.prepareStatement("INSERT INTO rooms (id, name, capacity) VALUES (?, ?, ?)");){
            ptmt.setString(1, id);
            ptmt.setString(2, name);
            ptmt.setInt(3, capacity);
            ptmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("放映厅 " + name + " 添加成功！");
        LogService.logAction(username,"添加放映厅 " + name);
    }

    // 修改放映厅信息
    private static void handleUpdateScreeningRoom() {
        String id = InputUtils.inputString("请输入要修改的放映厅ID: ");
        String name = ScreeningRoomService.getRoomById(id);
        int Capacity= ScreeningRoomService.getCapacityById(id);

        if (name == null) {
            System.out.println("放映厅不存在！");
            return;
        }

        System.out.println("当前放映厅信息:");
        System.out.printf("ID: %s\n名称: %s\n座位数: %d\n",id, name,Capacity);

        String new_name = InputUtils.inputString("请输入新的放映厅名称(留空不修改): ");
        String capacityStr = InputUtils.inputString("请输入新的座位数(留空不修改): ");
        int new_capacity = capacityStr.isEmpty() ? Capacity : Integer.parseInt(capacityStr);

        // 如果用户输入为空，则使用原来的值
        if (new_name.isEmpty()) new_name =name;

        ScreeningRoomService.updateRoom(id, new_name, new_capacity);
        System.out.println("放映厅信息更新成功！");
    }

    // 删除放映厅
    private static void handleDeleteScreeningRoom() {
        String id = InputUtils.inputString("请输入要删除的放映厅ID: ");
        ScreeningRoomService.deleteRoom(username,id);
        System.out.println("放映厅删除成功！");
    }

    // 显示场次管理菜单
    private static void showScreeningManagementMenu() {
        System.out.println("\n===== 场次管理 =====");
        System.out.println("1. 查看所有场次");
        System.out.println("2. 添加场次");
        System.out.println("3. 修改场次信息");
        System.out.println("4. 删除场次");
        System.out.println("5. 返回上一级");
        System.out.println("====================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                showAllScreenings();
                break;
            case 2:
                handleAddScreening();
                break;
            case 3:
                handleUpdateScreening();
                break;
            case 4:
                handleDeleteScreening();
                break;
            case 5:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    private static void showAllScreenings() {
        System.out.println("\n===== 场次列表 =====");
        try(PreparedStatement ptmt=conn.prepareStatement("SELECT id, movie, room, start_time, price FROM screening")){
            System.out.printf("%-10s %-20s %-15s %-20s %-10s\n", "ID", "电影名称", "放映厅", "开始时间", "票价");
            ResultSet rs=ptmt.executeQuery();
            while(rs.next()) {
                String id = rs.getString("id");
                String movie = rs.getString("movie");
                String room = rs.getString("room");
                String startTime = rs.getString("start_time");
                double price = rs.getDouble("price");
                System.out.printf("%-10s %-20s %-15s %-20s %-10.2f\n", id, movie, room, startTime, price);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("===================");
    }

    private static void handleAddScreening() {
        System.out.println("可用电影:");
        showAllMovies();

        String movieId = InputUtils.inputString("请输入电影ID: ");
        String title = MovieService.getMovieById(movieId);

        if (title== null) {
            System.out.println("电影不存在！");
            return;
        }

        System.out.println("可用放映厅:");
        showAllScreeningRooms();

        String roomId = InputUtils.inputString("请输入放映厅ID: ");
        String room= ScreeningRoomService.getRoomById(roomId);

        if (room == null) {
            System.out.println("放映厅不存在！");
            return;
        }

        String startTime = InputUtils.inputString("请输入开始时间(格式: yyyy-MM-dd HH:mm): ");
        double price = InputUtils.inputInt("请输入票价: ");

        String screeningId = "S" + System.currentTimeMillis();
        ScreeningService.addScreening(screeningId, movieId, roomId, startTime, price);
        System.out.println("场次添加成功！");
    }

    private static void handleUpdateScreening() {
        System.out.println("可用场次:");
        showAllScreenings();
        String movie;
        String room;
        String startTime;
        double price;
        String screeningId = InputUtils.inputString("请输入要修改的场次ID: ");
        try(PreparedStatement ptmt=conn.prepareStatement("SELECT * FROM screening WHERE id=?")){
            ptmt.setString(1,screeningId);
            ResultSet rs=ptmt.executeQuery();
            if(!rs.next()){
                System.out.println("该场次不存在");
                return;
            }
            System.out.println("当前场次信息:");
            movie=rs.getString("movie");
            room=rs.getString("room");
            startTime=rs.getString("start_time");
            price=rs.getDouble("price");
            System.out.printf("ID: %s\n电影: %s\n放映厅: %s\n开始时间: %s\n票价: %.2f\n", screeningId, movie, room, startTime, price);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("可用电影:");
        showAllMovies();
        String new_movie = InputUtils.inputString("请输入新的电影(留空不修改): ");

        System.out.println("可用放映厅:");
        showAllScreeningRooms();
        String new_room = InputUtils.inputString("请输入新的放映厅(留空不修改): ");

        String new_startTime = InputUtils.inputString("请输入新的开始时间(格式: yyyy-MM-dd HH:mm)(留空不修改): ");
        String priceStr = InputUtils.inputString("请输入新的票价(留空不修改): ");
        double new_price = priceStr.isEmpty() ? price: Double.parseDouble(priceStr);

        // 如果用户输入为空，则使用原来的值
        if (new_movie.isEmpty()) new_movie =movie;
        if (new_room.isEmpty()) new_room = room;
        if (new_startTime.isEmpty()) new_startTime = startTime;

        ScreeningService.updateScreening(screeningId, new_movie, new_room, new_startTime,new_price);
        System.out.println("场次信息更新成功！");
    }

    private static void handleDeleteScreening() {
        System.out.println("可用场次:");
        showAllScreenings();

        String screeningId = InputUtils.inputString("请输入要删除的场次ID: ");
        if(ScreeningService.deleteScreening(screeningId)) {
            System.out.println("场次删除成功！");
        }
        else{
            System.out.println("该场次不存在");
        }
    }

    private static void showSalesStatistics() {
        System.out.println("\n===== 销售统计 =====");
//        List<Order> orders = OrderService.getAllOrders();

        double totalSales = 0;
        int totalTickets = 0;

        // 按电影统计
        Map<String, Integer> movieSales = new HashMap<>();
        try(PreparedStatement ptmt=conn.prepareStatement("SELECT * FROM orders")){
            ResultSet rs=ptmt.executeQuery();
            while (rs.next()) {
                String dbstring=rs.getString("seat");
                String[]  seats = dbstring.split(",");
                if (rs.getString("state").equals("已支付")) {
                    totalSales += rs.getDouble("price");
                    totalTickets += seats.length;

                    String movieName = rs.getString("title");
                    movieSales.put(movieName, movieSales.getOrDefault(movieName, 0) + seats.length);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        System.out.printf("总销售额: %.2f 元\n", totalSales);
        System.out.printf("总售票数: %d 张\n", totalTickets);

        System.out.println("\n电影销售统计:");
        for (Map.Entry<String, Integer> entry : movieSales.entrySet()) {
            System.out.printf("%s: %d 张\n", entry.getKey(), entry.getValue());
        }

        System.out.println("===================");
    }

    private static void showReceptionistMenu() {
        System.out.println("\n===== 前台菜单 =====");
        System.out.println("1. 密码管理");
        System.out.println("2. 查看场次");
        System.out.println("3. 售票");
        System.out.println("4. 退票");
        System.out.println("5. 查看订单");
        System.out.println("6. 退出登录");
        System.out.println("====================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                showReceptionistPasswordMenu();
                break;
            case 2:
                showAvailableScreenings();
                break;
            case 3:
                handleSellTicket();
                break;
            case 4:
                handleRefundTicket();
                break;
            case 5:
                showMyOrders();
                break;
            case 6:
                System.out.println("退出登录成功！");
                username= null;
                break;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    private static void showReceptionistPasswordMenu() {
        System.out.println("\n===== 密码管理 =====");
        System.out.println("1. 修改自身密码");
        System.out.println("2. 返回上一级");
        System.out.println("====================");

        int choice = InputUtils.inputInt("请选择操作: ");

        switch (choice) {
            case 1:
                handleChangeOwnPassword();
                break;
            case 2:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    private static void showAvailableScreenings() {
        System.out.println("\n===== 可用场次 =====");
        try(PreparedStatement ptmt=conn.prepareStatement("SELECT * FROM screening")) {
            ResultSet rs = ptmt.executeQuery();
            System.out.printf("%-10s %-20s %-15s %-20s %-10s %-10s\n", "ID", "电影名称", "放映厅", "开始时间", "票价", "剩余座位");
            while (rs.next()) {
                String id = rs.getString("id");
                String movie = rs.getString("movie");
                String room = rs.getString("room");
                int capacity=ScreeningRoomService.getCapacityByName(room);
                String startTime = rs.getString("start_time");
                double price = rs.getDouble("price");
                System.out.printf("%-10s %-20s %-15s %-20s %-10.2f %-10d\n", id, movie, room, startTime, price,capacity);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("===================");
    }

    private static void handleSellTicket() {
        showAvailableScreenings();
        int[][] seat = new int[10][10];

        String screeningId = InputUtils.inputString("请输入要购票的场次ID: ");
        // 显示座位图
        System.out.println("\n===== 座位图 =====");
        System.out.println("  0 1 2 3 4 5 6 7 8 9");
        String room=ScreeningRoomService.getRoomById(screeningId);
        if(room==null){
            System.out.println("场次不存在！");
            return;
        }
        double price=ScreeningRoomService.getPriceId(screeningId);
        try(PreparedStatement ptmt=conn.prepareStatement("SELECT seat FROM orders WHERE room=?")) {
            ptmt.setString(1,room);
            ResultSet rs= ptmt.executeQuery();
            while (rs.next()) {
                int row,col;
                String dbseat = rs.getString("seat");
                String[] parts = dbseat.split(",");
                for(int i=0;i<parts.length;i+=2) {
                    row = Integer.parseInt(parts[0]);
                    col = Integer.parseInt(parts[1]);
                    seat[row][col] = 1;
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        int Capacity=ScreeningRoomService.getCapacityByName(room);
        for (int i = 0; i < seat.length; i++) {
            System.out.print(i + " ");
            for (int j = 0; j < seat[i].length&&(i*10+j<=Capacity); j++) {
                System.out.print(seat[i][j] == 1 ? "X " : "O ");
            }
            System.out.println();
        }
        System.out.println("O: 可选座位, X: 已售座位");
        System.out.println("===================");
        List<Integer[]> selectedSeats = new ArrayList<>();

        while (true) {
            String seatInput = InputUtils.inputString("请输入座位号(格式: 行,列，如: 1,2。输入空结束选座): ");

            if (seatInput.isEmpty()) {
                break;
            }

            String[] parts = seatInput.split(",");
            if (parts.length != 2) {
                System.out.println("格式错误，请重新输入！");
                continue;
            }

            try {
                int row = Integer.parseInt(parts[0]);
                int col = Integer.parseInt(parts[1]);

                if (row < 0 || row >= 10 || col < 0 || col >= 10||row*10+col>=Capacity) {
                    System.out.println("座位号超出范围，请重新输入！");
                    continue;
                }

                if (seat[row][col] == 1) {
                    System.out.println("该座位已售出，请重新选择！");
                    continue;
                }

                selectedSeats.add(new Integer[]{row, col});
                System.out.println("已选择座位: " + row + "," + col);
            } catch (NumberFormatException e) {
                System.out.println("格式错误，请输入数字！");
            }
        }

        if (selectedSeats.isEmpty()) {
            System.out.println("未选择任何座位，购票取消！");
            return;
        }

        // 创建订单
        String orderId = OrderService.createOrder(username, screeningId, selectedSeats);

        if (orderId != null) {
            System.out.println("订单创建成功！订单号: " + orderId);
            System.out.printf("总价: %.2f 元\n", selectedSeats.size() * price);

            // 立即支付
            if (InputUtils.confirm("是否立即支付？")) {
                OrderService.payOrder(username,orderId);
                System.out.println("支付成功！");
            }
        } else {
            System.out.println("购票失败！");
        }
    }

    private static void handleRefundTicket() {
        System.out.println("\n===== 我的订单 =====");
        showMyOrders();

        String orderId = InputUtils.inputString("请输入要退票的订单ID: ");
        OrderService.cancelOrder(username,orderId);
        System.out.println("退票成功！");
    }

    private static void showMyOrders() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        System.out.printf("%-15s %-20s %-15s %-20s %-10s %-10s %s\n",
                "订单号", "电影名称", "放映时间", "座位", "总价", "状态", "下单时间");
        try(PreparedStatement ptmt=conn.prepareStatement("SELECT * FROM orders WHERE user_name=?")) {
            ptmt.setString(1,username);
            ResultSet rs= ptmt.executeQuery();
            while (rs.next()) {
                System.out.printf("%-15s %-20s %-15s %-20s %-10.2f %-10s %s\n",rs.getString("order_id"),
                        rs.getString("title"),
                        rs.getString("stime"),
                        rs.getString("seat"),
                        rs.getDouble("price"),
                        rs.getString("state"),
                        rs.getString("order_time"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("===================");
    }
}
